﻿using Demo.DBContext;
using Demo.Entities;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Demo.DtoParameters;
using Demo.Helpers;

namespace Demo.Repository
{
    public class CompanyRepository : ICompanyRepository
    {
        private readonly RoutineDbContext _context;

        public CompanyRepository(RoutineDbContext context)
        {
            _context = context ?? throw new ArgumentNullException(nameof(context));
        }

        public async Task<PageList<Company>> GetCompaniesAsync(CompanyDtoParameters parameters)
        {
            if (parameters == null) throw new ArgumentNullException(nameof(parameters));

            var item = _context.Companies as IQueryable<Company>;

            if (!string.IsNullOrWhiteSpace(parameters.CompanyName))
            {
                item = item.Where(et => et.Name.Contains(parameters.CompanyName));
            }

            if (Equals(!string.IsNullOrWhiteSpace(parameters.SearchTerm)))
            {
                item = item.Where(et =>
                    et.Name.Contains(parameters.CompanyName) || et.Introduction.Contains(parameters.SearchTerm));
            }


            return await PageList<Company>.CreateAsync(item, parameters.PageNumber, parameters.PageSize);
        }

        public async Task<Company> GetCompanyAsync(Guid companyId)
        {
            return await _context.Companies.FirstOrDefaultAsync(et => et.Id == companyId);
        }

        public async Task<IEnumerable<Company>> GetCompaniesAsync(IEnumerable<Guid> companyIds)
        {
            return await _context.Companies.Where(et => companyIds.Contains(et.Id))
                .OrderBy(et => et.Name)
                .ToListAsync();
        }

        public void AddCompany(Company company)
        {
            _context.Companies.Add(company);
        }

        public void DeleteCompany(Company company)
        {
            _context.Companies.Remove(company);
        }

        public void UpdateCompany(Company company)
        {
            throw new NotImplementedException();
        }

        public async Task<bool> CompanyExistsAsync(Guid companyId)
        {
            return await _context.Companies.AnyAsync(et => et.Id == companyId);
        }

        public async Task<int> SaveAsync()
        {
            return await _context.SaveChangesAsync();
        }
    }
}